package com.myworkbench.workbench.domain.entity.role;

import com.myworkbench.workbench.domain.Identity;
import com.myworkbench.workbench.domain.entity.resource.Resource;
import com.myworkbench.workbench.domain.entity.resource.ResourceId;
import com.myworkbench.workbench.domain.entity.user.User;
import com.myworkbench.workbench.domain.valueobject.Creator;
import com.myworkbench.workbench.domain.valueobject.Updator;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.Assert;

import javax.persistence.*;
import java.util.HashMap;
import java.util.Set;

@Data
@Table
@Entity
@AllArgsConstructor
@NoArgsConstructor
@NamedNativeQuery(name = "Role.findAllRoleByUserId", query = RoleNamedSQL.findAllRolesBy, resultClass = Role.class)
public class Role extends Identity<Role> {
    public Role(Integer id) {
        super(id);
    }

    @Column(length = 50, nullable = false)
    private String name;
    /**
     * 角色描述
     */
    @Column(length = 200, nullable = false)
    private String roleDesc;

    private Short isDelete;

    @Embedded
    @ElementCollection(fetch = FetchType.LAZY)
    @CollectionTable(name="rel_role_resource",
            joinColumns ={@JoinColumn(name = "role_id")})
    @AttributeOverrides({ @AttributeOverride(name="id",column = @Column(name="resource_id"))})
    private Set<ResourceId> resoureceIds;

    /**
     * 角色赋值资源
     * @param resourceIds
     */
    public void grantResources(Set<ResourceId> resourceIds){
        Assert.notEmpty(resourceIds,"roleIds is null");
        Role role = get();
        Assert.notNull(role,"user is null ");
        role.setResoureceIds(resourceIds);
        role.update();
    }

    /**
     * 值对象
     */
    private Creator creator;
    private Updator updator;

}
